import React from 'react'
import Toast from 'antd-mobile/lib/toast';
import Modal from 'antd-mobile/lib/modal';
import ReactDOM from 'react-dom';
import AddSuccess from 'shared/components/AddCareSuccess';
import localStorage from 'shared/utils/localStorage';
import {
  addToCart, addWishApi,
  delWishApi, fetchcancelOrderApi,
  wxpayApi, appid, bindCouponApi
} from '../api';

const alert = Modal.alert;

//加入购物车
export const addCartFetch = (product_id, quantity) => {
  Toast.loading();
  const sessid = localStorage.get('sessId');
  return addToCart({ product_id, quantity, sessid }).then((res)=>{
    if(res.code === 1000){
      Toast.hide();
      const doc = window.document;
      const node = doc.createElement('div');
      doc.body.appendChild(node);
      ReactDOM.render(<AddSuccess show />, node);
    }else{
      Toast.error(res.data);
    }
  })
}

export const addWish = product_id => {
  if (!window.localStorage.getItem('userInfo')) {
    alert('是否登录', '', [
      { text: '取消', onPress: () => console.log('cancel'), style: 'default' },
      { text: '确定', onPress: () => __self.history.push('/Login') },
    ]);
    return false;
  }

  return addWishApi({ product_id }).then((res) => {
    if (res.code === 1000) {
      Toast.success('关注成功！', 1);
    }
    return res;
  })
}

export const delWish = product_id => delWishApi({ product_id }).then((res)=>{
  if(res.code === 1000){
    Toast.success('取消关注成功！', 1);
  }
  return res;
})

export const bindCoupon = (couponCode) => {
  if (couponCode) {
    bindCouponApi({ code: couponCode }).then((res) => {
      const { code } = res;
      if (code === 1000) {
        this.props.onHandleCoupon({ coupon_id: res.data.coupon_id });
        Toast.success('兑换成功', 1)
      } else if (code === 1003){
        Toast.fail('此优惠码已经使用过', 1)
      } else if (code === 1002){
        Toast.fail('此优惠码无效', 1)
      } else if (code === 1002){
        Toast.fail('已绑定过此优惠劵', 1)
      }
    })
  } else {
    Toast.fail('兑换码不能为空', 1)
  }
}

export const cancelOrder = order_id => fetchcancelOrderApi({ order_id }).then((res)=>{
  if(res.code === 1000){
    Toast.success('取消订单成功！', 1);
    window.location.reload();
  }
})

export const wxpayh5Pay = (param) => {
  wxpayApi({ ...param, wxpayjsapi: 1, wxpayh5: 0 }).then(res => {
    if (res.code === 1000) {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          appId: appid,     //公众号名称，由商户传入
          timeStamp:  res.data.timeStamp,         //时间戳，自1970年以来的秒数
          nonceStr: res.data.nonceStr, //随机串
          package:  res.data.package,
          signType: "MD5",         //微信签名方式：
          paySign:  res.data.paySign //微信签名
        },
        function(res){
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            __self.history.push('/account/order')
          }
        }
      );
    } else {
      Toast.info('服务端错误')
    }
  })
}
